package util

import (
	"encoding/json"
)

// Helper tools for structs, like map to struct | or struct to map
// !! TODO: Reduce dependency

// StructToMap converts struct to map
func StructToMap(fromStruct interface{}) map[string]interface{} {
	d, err := json.Marshal(fromStruct)
	if err != nil {
		// !! TODO: no panic
		panic(err)
	}
	m := make(map[string]interface{})
	err = json.Unmarshal(d, &m)
	if err != nil {
		// !! TODO: no panic
		panic(err)
	}

	return m
}

// MapToStruct converts map to struct
// Output must be pointer
func MapToStruct(input interface{}, output interface{}) error {
	// err := mapstructure.Decode(input, output)
	// return err
	d, err := json.Marshal(input)
	if err != nil {
		return err
	}

	err = json.Unmarshal(d, &output)
	if err != nil {
		return err
	}

	return nil
}
